import 'dart:async';
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;
import '../http/Url.dart';
import '../model/configModel.dart';
import '../util/header_util.dart';

class TranslateDao {
  static Utf8Decoder utf8decoder = const Utf8Decoder();

  ///翻译
  static Future<void> translate(
      BuildContext context, String googlekey, String content) async {
    var locale = Localizations.localeOf(context);
    var httpurl = Uri.parse('https://translation.googleapis.com/language/translate/v2');

    final bodyParams = {
      'key': googlekey,
      'target': locale.languageCode,
      'q': content,
      'format': 'text'
    };
    try {
      var response = await http.post(httpurl,
          body: jsonEncode(bodyParams),
          headers: {'Content-Type':'application/json'})
          .timeout(const Duration(seconds: 10));
      if (response.statusCode == 200) {
        var responseBody = jsonDecode(response.body);
        // // 假设翻译结果存储在responseBody的'data' -> 'translations'数组中的第一个元素的'translatedText'字段
        // return responseBody['data']['translations'][0]['translatedText'];
      } else {
        throw Exception('Failed to translate: ${response.statusCode}');
      }
    } on TimeoutException catch (e) {
      // 处理超时异常
      debugPrint('Request timed out: ${e.message}');
      throw Exception('Translation request timed out.');
    } catch (e) {
      // 处理其他异常
      debugPrint('Error during translation: ${e.toString()}');
      throw Exception('An error occurred during translation.');
    }
  }

  ///使用该接口获取融云key和谷歌翻译Key。
  static Future<String> getGoogleTranslationKey(
      {String keyName = 'google_translation_key'}) async {
    String keyString = '';
    var uri = Uri.parse("${AppUrl.getAppConfig}?ver=0");
    var response = await http.get(uri,
        headers: await HeaderUtil().getHeader(config: true));
    String bodyString = utf8decoder.convert(response.bodyBytes);

    if (response.statusCode == 200) {
      var result = json.decode(bodyString);
      ConfigModel configModel = ConfigModel.fromJson(result['data']);
      configModel.items?.forEach((element) {
        if (element.name.toString() == keyName) {
          keyString = element.data ?? "";
        }
      });
    } else {
      throw Exception('"Request failed with status: ${response.statusCode}"');
    }
    return keyString;
  }
}
